<?php
namespace App\Common;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Validator;

class SendsmsController extends Controller{
    private $sms_templt = [];
    private $sms_autograph = '【万有云】';
    public function __construct()
    {
        $this->sms_templt = [
            'reg' => [
                'fivec_sms' => '您的验证码为：{code},有效期为15分钟，请及时操作。',
                'aliyun_sms' => '1234',
            ],
        ];
    }
    /*
     * 发送验证码
     */
    public function sendSms($mobile='',$sms_code='',$code='',$ip='127.0.0.1'){
        /*
         * 验证手机号码格式是否有效
         */
        $validator = Validator::make(['mobile'=>$mobile],[
            'mobile' => 'bail|required|mobile',
        ],[
            'phone.mobile' => '请输入11位有效手机号码',
        ]);
        if ($validator->fails()) {
            $errors = json_decode($validator->messages(),true);
            reset($errors);
            return [
                'code' => '-1',
                'msg' => $validator->errors()->first(),
                'field' => key($errors),
            ];
        }
        /*
         * 验证发的短信模板是否存在
         */
        if(! $this->sms_templt[$sms_code]){
            return [
                'code' => '-2',
                'msg' => '请选择短信模板',
                'field' => 'sms_code',
            ];
        }
        /*
         * 生成验证码
         */
        $code = ($code =='' ? rand(100000,999999) : $code);

        /*
         * 一段时间内该手机号申请多少次验证码码，记录
         */
        $SmsModel = new \App\Model\Sms();
        $sms_s = $SmsModel->getSmsAll($mobile);

        /*
         * 发送短信次数 > 20 估计是刷短信的，不弄让他在胡来了
         */
        if(count($sms_s) > 20){
            return [
                'code' => '-3',
                'msg' => '短信获取过于频繁，请过一段时间再试吧！',
                // 'field' => 'mobile',
            ];
        }
        if(count($sms_s) != 0){
            reset($sms_s);
            $sms_first = current($sms_s);

            if((time() - $sms_first['create_time']) < 60){
                return [
                    'code' => '1',
                    'msg' => '发送成功 ！',
                ];
            }

            $sms_count = 0;
            foreach ($sms_s as $k=>$v) {
                if($v['type'] == $sms_code){
                    $sms_count++;
                }
            }
            if($sms_count > 4){
                return [
                    'code' => '-4',
                    'msg' => '短信获取过于频繁，请过一段时间再试吧！',
                    // 'field' => 'mobile',
                ];
            }
        }
        /*
         * 验证全部通过，说明该次发短信有效，可以发短信了
         * 先插入发送记录在发送短信
         * 下面的发送短信的平台 阿里云$this->sendSmsAli、美联短信$this->sendSms5c
         */
        $sms_id = $SmsModel->createDate(['mobile'=>$mobile,'type'=>$sms_code,'code'=>$code,'ip'=>$ip]);
        if($sms_id > 0){
            // $this->sendSms5c($mobile,$sms_code,$code);
            // $this->sendSmsAli($mobile,$sms_code,$code);

            session([$mobile.'_'.$sms_code.'_code'=>['ip'=>$ip,'code'=>$code,'time'=>time()+60*15]]);
            return [
                'code' => '1',
                'msg' => '发送成功！',
                'abc' => session($mobile.'_'.$sms_code.'_code','000000'),
            ];
        }else{
            return [
                'code' => '0',
                'msg' => '发送失败，请重新尝试',
                // 'field' => 'mobile',
            ];
        }
    }
    /*
     * 验证验证码
     */
    public function checkSmscode($mobile='',$sms_code='',$code='',$ip='127.0.0.1'){
        $session_info = session($mobile.'_'.$sms_code.'_code',null);
        if(!$session_info){
            return [
                'code' => '-1',
                'msg' => '验证码不存在',
            ];
        }
        if($session_info['ip'] != $ip){
            return [
                'code' => '-2',
                'msg' => '无效验证码',
            ];
        }
        if($session_info['time'] < time()){
            return [
                'code' => '-3',
                'msg' => '验证码超时',
            ];
        }
        if($session_info['code'] != $code){
            return [
                'code' => '-4',
                'msg' => '验证码错误',
            ];
        }
        session([$mobile.'_'.$sms_code.'_code'=>null]);
        return [
            'code' => '1',
            'msg' => '验证通过',
        ];
    }

    // 美联软通短信
    private function sendSms5c($mobile,$sms_code,$code){
        $encode='UTF-8';
        $username='hgdx';  //用户名
        $password_md5=md5('a123456');  //32位MD5密码加密，不区分大小写
        $apikey='d3828bf70247908e67b86fcc64f3de98';  //apikey秘钥（请登录 http://m.5c.com.cn 短信平台-->账号管理-->我的信息 中复制apikey）
        $content = $this->sms_autograph.$this->sms_code[$sms_code]['fivec_sms'];

        $content = preg_replace('{code}',$code,$content);

        $contentUrlEncode = urlencode($content);//执行URLencode编码  ，$content = urldecode($content);解码

        //发送链接（用户名，密码，apikey，手机号，内容）
        $url = "http://m.5c.com.cn/api/send/index.php?";  //.5c.com.cn】修改为IP：【115.28.23.78】
        $data=array(
            'username'=>$username,
            'password_md5'=>$password_md5,
            'apikey'=>$apikey,
            'mobile'=>$mobile,
            'content'=>$contentUrlEncode,
            'encode'=>$encode,
        );
        $result = $this->curl_sms($url,$data);
        return $result;
    }
    // 阿里云短信
    private function sendSmsAli($mobile,$sms_code,$code){

        AlibabaCloud::accessKeyClient('<accessKeyId>', '<accessSecret>')->regionId('cn-hangzhou')->asDefaultClient();

        $content = $this->sms_code[$sms_code]['aliyun_sms'];

        try{
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https')
                ->verify('2017-05-25')
                ->accept('SendSms')
                ->method('POST')
                ->options([
                    'query' => [

                    ]
                ])
                ->request();

            return $result->toArray();
        }catch(ClientException $e){
            return $e->getErrorMessage().PHP_EOL;
        }catch(ServerException $e){
            return $e->getErrorMessage().PHP_EOL;
        }
    }

    private function curl_sms($url,$post_fields=array()){
        /*
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);//用PHP取回的URL地址（值将被作为字符串）
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//使用curl_setopt获取页面内容或提交数据，有时候希望返回的内容作为变量存储，而不是直接输出，这时候希望返回的内容作为变量
        curl_setopt($ch,CURLOPT_TIMEOUT,30);//30秒超时限制
        curl_setopt($ch,CURLOPT_HEADER,1);//将文件头输出直接可见。
        curl_setopt($ch,CURLOPT_POST,1);//设置这个选项为一个零非值，这个post是普通的application/x-www-from-urlencoded类型，多数被HTTP表调用。
        curl_setopt($ch,CURLOPT_POSTFIELDS,$post_fields);//post操作的所有数据的字符串。
        $data = curl_exec($ch);//抓取URL并把他传递给浏览器
        curl_close($ch);//释放资源
        $res = explode("\r\n\r\n",$data);//explode把他打散成为数组
        return $res[2]; //然后在这里返回数组。
        */
    }
}
